// AdminService.java
package org.example.shop.service;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.example.shop.entity.Admin;
import org.example.shop.mapper.AdminMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class AdminService {
    @Resource
    private AdminMapper adminMapper;

    public Admin validateAdmin(String account, String password) {
        Admin admin = adminMapper.selectByAccount(account);
        if (admin == null) return null;

        String encryptedPwd = DigestUtils.md5DigestAsHex(password.getBytes());
        return encryptedPwd.equals(admin.getPassword()) ? admin : null;
    }

    public void updateLoginInfo(Admin admin, HttpServletRequest request) {
        admin.setLastLoginTime(String.valueOf(LocalDateTime.now()));
        admin.setLastLoginIp(getClientIp(request));
        adminMapper.updateLoginInfo(admin);
    }

    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}